<template>
	<view class="pages" :class="themeName">
		<!-- #ifndef  H5 -->
		<custom-navbar :is-back="true" title="注册" navigation-style="default"></custom-navbar>
		<!-- #endif -->
		<view class="register">
			<!-- #ifndef MP-WEIXIN-->
			<view class="register-text">手机号注册</view>
			<!-- #endif -->
			<view style="display: flex;justify-content: center;">
				<button class="butoo bot_tox" hover-class="none" open-type="chooseAvatar" @chooseavatar="chooseavatar"
					@click="chooseavatar">
					<image src="../../static/images/logo/UploadAvatar.png" v-if="avatarImage == ''"></image>
					<image :src="avatarImage" v-else></image>
				</button>
			</view>
			<!-- <button class="obtainSj bot_tox" @getphonenumber="getphonenumber" open-type="getPhoneNumber" >
			  获取手机号
			</button> -->
			<view class="input " style="margin-top: 130rpx;">
				<u-field label-width="0" v-model="register.nickname" :maxlength="4" placeholder="输入长度四位的名称" :border-bottom="false"
					:style="{ width: '100%' }">
					<template v-slot:icon>
						<image class="field-left-icon" src="/static/img/Home/sj3.png"></image>
					</template>
				</u-field>
			</view>
			<view class="input m-t-40" >
				<u-field label-width="0" v-model="register.mobile" placeholder="输入手机号" :border-bottom="false"
					:style="{ width: '100%' }" type="number">
					<template v-slot:icon>
						<image class="field-left-icon" src="/static/img/Home/sj3.png"></image>
					</template>
					<!-- <view slot="right">
					    <button class="sms-btn bot_tox" style="width: 168rpx;" @getphonenumber="getphonenumber" open-type="getPhoneNumber" >
					      获取手机号
					    </button>
					</view> -->
				</u-field>
			</view>
			

			<view class="input m-t-40" v-if="isRegisterCode">
				<u-field label-width="0" v-model="register.code" placeholder="短信验证码" :border-bottom="false"
					type="number">
					<template v-slot:icon>
						<image class="field-left-icon" src="/static/img/Home/yzm3.png"></image>
					</template>
					<view slot="right">
						<view class="sms-btn p-l-20" @tap="sendSMS">
							<!-- 获取验证码 -->
							<u-verification-code unique-key="login" ref="uCode" @change="codeChange">
							</u-verification-code>
							<view style="color:#ff8200; font-size:27rpx;" class="xs" :class="{
                                    disabled:
                                        codeTips == '获取验证码' && register.mobile.length !== 11,
                                }">
								{{ codeTips }}
							</view>
						</view>
					</view>
				</u-field>
			</view>
			<view class="input m-t-40">
				<u-field label-width="0" v-model="register.inviter_code" placeholder="好友邀请码" :border-bottom="false"
					:style="{ width: '100%' }">
					<template v-slot:icon>
						<image class="field-left-icon" src="/static/img/Home/yqm.png"></image>
					</template>
				</u-field>
			</view>
			<view class="input m-t-40" >
				<u-field label-width="0" v-model="register.password" :password="!pwdShow" type="text"
					:password-icon="false" placeholder="设置登录密码，6-20位数字、字母或字符" :border-bottom="false"
					:style="{ width: '100%' }">
					<template v-slot:icon>
						<image class="field-left-icon" src="/static/img/Home/mm2.png"></image>
					</template>
					<view slot="right">
						<u-icon name="eye" @click="pwdShow = !pwdShow" v-show="!pwdShow" size="36rpx">
						</u-icon>
						<u-icon name="eye-off" @click="pwdShow = !pwdShow" v-show="pwdShow" size="36rpx"></u-icon>
					</view>
				</u-field>
			</view>
			<view class="input m-t-40" >
				<u-field label-width="0" v-model="register.password_confirm" :password="!comfirmPwdShow" type="text"
					:password-icon="false" placeholder="确认登录密码" :border-bottom="false" :style="{ width: '100%' }">
					<template v-slot:icon>
						<image class="field-left-icon" src="/static/img/Home/mm2.png"></image>
					</template>
					<view slot="right">
						<u-icon name="eye" @click="comfirmPwdShow = !comfirmPwdShow" v-show="!comfirmPwdShow"
							size="36rpx">
						</u-icon>
						<u-icon name="eye-off" @click="comfirmPwdShow = !comfirmPwdShow" v-show="comfirmPwdShow"
							size="36rpx"></u-icon>
					</view>
				</u-field>
			</view>
			<view class="m-t-40">
				<u-checkbox v-model="isAgree" :active-color="themeColor" shape="circle" :label-disabled="true">
					<view class="sm flex">
						已阅读并同意
						<router-link data-theme="" to="/pagesUser/pages/server_explan/server_explan?type=1">
							<view class="agreement">《服务协议》</view>
						</router-link>
						和
						<router-link to="/pagesUser/pages/server_explan/server_explan?type=2">
							<view class="agreement">《隐私协议》</view>
						</router-link>
					</view>
				</u-checkbox>
			</view>
			<button class="btn white" style="margin-top: 180rpx;" :class="{ disabled: isDisabled }" @tap="registerFun">
				立即注册
			</button>
			<view class="inytr">

				<!-- #ifdef APP -->
				<!-- 只有app才有登录功能 -->
				<view class="ypolx" @click="login">登陆</view>
				<!-- #endif -->

				<!-- #ifdef H5 -->
				<view class="ypolx1" @click="ppolci">立即下载APP</view>
				<!-- <view class="ypolx1" @click="wananchi">关注公众号</view> -->
				<!-- #endif -->
			</view>

			<!-- #ifdef H5 -->
			<view class="m-t-40" v-if="isDevelopment" @click="multipleRegisterHandler"
				style="padding: 30rpx;color:#000000;">
				调试模式，一键注册多个账号
			</view>
			<!-- #endif -->

		</view>
		<user-agreement-modal :is-agree.sync="isAgree" :visible.sync="showModel"></user-agreement-modal>
		<u-popup v-model="registerSussuesVisible" mode="center">
			<view class="register-susses-popup-content">
				<image style="width: 106rpx;height:106rpx;" src="/static/img/Home/sj3.png"></image>
				<view class="tip">注册成功</view>
				<view>
					<!-- #ifdef H5 -->
					<u-button class="btn" type="primary" @click="ppolci">立即下载APP</u-button>
					<!-- #endif -->

					<!-- #ifndef H5 -->
					<u-button class="btn" type="primary" @click="login">立即登陆</u-button>
					<!-- #endif -->
				</view>
			</view>
		</u-popup>
		<!-- 公众号功能，暂时不需要。 2024-05-15 xjp -->
		<!-- <u-popup v-model="onShow" mode="center">
			<view class="wananchi_list">
				<view>
					长按识别关注公众号
				</view>
				<image :src="wechatQrcode"></image>
			</view>
		</u-popup> -->
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex';
	import request from '@/utils/request'
	console.log("process.env", process.env)
	import {
		apiAccountRegister,
		apiCheckMobile,
		apiRegisterCaptcha,
		apiRegisterGetPhone
	} from '@/api/app';
	import {
		trottle
	} from '@/utils/tools';
	import {
		uploadFile
	} from '@/utils/tools.js'
	import Cache from '@/utils/cache'
	import config from '@/config/app.js'
	import {
		apiConfig
	} from '@/api/app'
	export default {
		name: "register",
		data() {
			return {
				registerSussuesVisible: false,
				onShow: false,
				register: {
					mobile: "",
					code: "",
					password: "",
					password_confirm: "",
					inviter_code: '',
					avatar: '',
					user_id: '',
					nickname:''
				},
				codeTips: "",
				isAgree: false, // 是否同意协议
				pwdShow: false,
				comfirmPwdShow: false,
				showModel: false,
				wechatQrcode: '',
				isDevelopment: false,
				avatarImage: ''
			};
		},
		methods: {
			async getphonenumber(e) {
				apiRegisterGetPhone({
					js_code: e.detail.code
				}).then(res => {
					this.register.mobile = res.phoneNumber
				})
			},
			chooseavatar(e) {
				// #ifndef MP-WEIXIN
				// 此为uView的跳转方法，详见"文档-JS"部分，也可以用uni的uni.navigateTo
				this.$Router.push({
					// 关于此路径，请见下方"注意事项"
					path: '/components/uview-ui/components/u-avatar-cropper/u-avatar-cropper',
					// 内部已设置以下默认参数值，可不传这些参数
					query: {
						// 输出图片宽度，高等于宽，单位px
						destWidth: 300,
						// 裁剪框宽度，高等于宽，单位px
						rectWidth: 200,
						// 输出的图片类型，如果'png'类型发现裁剪的图片太大，改成"jpg"即可
						fileType: 'jpg'
					}
				})
				// #endif
				console.log(e);
				// #ifdef MP-WEIXIN
				if (e.detail.avatarUrl) {
					this.uploadImage(e.detail.avatarUrl)
					this.avatarImage = e.detail.avatarUrl
				}
				// #endif

			},

			uploadImage(path) {
				uni.showLoading({
					title: '正在上传中...',
					mask: true
				})
				console.log(path);
				uploadFile(path)
					.then((res) => {
						this.register.avatar = res.url
						this.avatarImage = config.ImageURL + '/' + res.url
						// this.avatarImage = res.url
						uni.hideLoading()
						console.log(this.avatarImage, 'this.avatarImage', config.ImageURL);
					})
					.catch(() => {
						uni.hideLoading()
						this.$toast({
							title: '上传失败'
						})
					})
			},

			codeChange(tip) {
				this.codeTips = tip;
			},
			wananchi() {

				this.onShow = true
			},
			login() {
				// uni.redirectTo({
				// 	url:"/pages/login/login"
				// });
				uni.redirectTo({
					url: "/pages/index/index"
				});
			},
			ppolci() {
				let setting = uni.getStorageSync('self_config');
				apiConfig().then(res => {
					var u = navigator.userAgent,
						app = navigator.appVersion;
					var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android终端或者uc浏览器 
					var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

					if (isAndroid) {
						//Android 
						window.location.href = res.android_download_url;
					} else {
						//ios     
						window.location.href = res.ios_download_url;
					}
				})
			},
			async registerFun() {
				const vm = this
				let {
					mobile,
					password,
					code,
					inviter_code,
					password_confirm,
					avatar
				} = this.register;
				if (!mobile) {
					this.$toast({
						title: "请输入手机号",
					});
					return;
				}
				if (!inviter_code) {
					this.$toast({
						title: "请输入邀请码",
					});
					return;
				}
				if (!password) {
				    this.$toast({
				        title: "请输入密码",
				    });
				    return;
				}
				if (!password) {
				    this.$toast({
				        title: "请再次输入密码",
				    });
				    return;
				}
				if (password != password_confirm) {
				    this.$toast({
				        title: "两次密码输入不一致",
				    });
				    return;
				}
				if (!this.isAgree) {
					// this.$toast({ title: "请阅读并同意《服务协议》《隐私协议》" });
					this.showModel = true;
					return;
				}
				if (avatar == '') {
					this.$toast({
						title: "请上传头像",
					});
					return;
				}
				await apiAccountRegister(this.register).then((res) => {
					this.$toast({
						title: "注册成功",
					});

					// setTimeout(() => {
					//  this.onShow = true;
					// }, 1000);
					// app 小程序 平台，需要用户跳到登录页面
					// #ifdef MP-WEIXIN
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/index/index'
						});
					}, 1000)
					// #endif

					// h5平台，引导用户下载
					// #ifdef H5 
					this.registerSussuesVisible = true
					// #endif

				});
			},
			async sendSMS() {
				if (!this.$refs.uCode.canGetCode) return;
				if (!this.register.mobile) {
					this.$toast({
						title: "请输入手机号",
					});
					return;
				}
				/**
				 * @descriptionp 检测手机号是否已经注册
				 */
				const {
					has
				} = await apiCheckMobile({
					mobile: this.register.mobile
				});
				if (has === 1) {
					return this.$toast({
						title: "手机号已被注册",
					});
				}
				apiRegisterCaptcha({
						mobile: this.register.mobile,
					})
					.then((res) => {
						this.$refs.uCode.start();
					})
					.catch((err) => {
						console.log(err);
					});
			},
			/**
			 * 调试模式下，一键注册多个账号
			 */
			multipleRegisterHandler() {
				const configList = []
				const vm = this
				for (let i = 0; i <= 9; i++) {
					apiAccountRegister({
						...vm.register,
						mobile: `1771234567${i}`,
					})
					apiAccountRegister({
						...vm.register,
						mobile: `1371234567${i}`,
					})
				}
			},
			developmentHandler(params = {}) {
				let NODE_ENV = ''
				try {
					NODE_ENV = process.env.NODE_ENV
				} catch (e) {
					NODE_ENV = ''
					//TODO handle the exception
				}
				if (NODE_ENV !== 'development') {

					return
				}
				this.isDevelopment = true
				const {
					inviter_code
				} = params
				console.log(inviter_code, 'inviter_code');
				this.register.inviter_code = inviter_code || Cache.get('invite_code') || 'CDZQJL'
				this.register.code = '8888'
				this.register.password = 'ces123456'
				this.register.password_confirm = 'ces123456'
				this.isAgree = true // 是否同意协议
				this.pwdShow = true
				this.comfirmPwdShow = true
			}
		},
		computed: {
			isRegisterCode() {
				const {
					is_mobile_register_code
				} = this.appConfig;
				return is_mobile_register_code;
			},
			isDisabled() {
				//TODO
				if (this.isRegisterCode) {
					if (
						this.register.mobile.length == 11 &&
						this.register.code &&
						this.register.password &&
						this.register.password_confirm
					) {
						return false;
					} else {
						return true;
					}
				} else {
					if (
						this.register.mobile.length == 11 &&
						this.register.password &&
						this.register.password_confirm
					) {
						return false;
					} else {
						return true;
					}
				}
			},
		},
		onLoad(e) {
			setTimeout(() => {
				// 监听从裁剪页发布的事件，获得裁剪结果
				uni.$on('uAvatarCropper', (path) => {
					this.uploadImage(path)
				})
				this.register.user_id = e.id
				// 邀请码？如果是分享的，会带一个code, 如果不是，则检测环境。
				this.register.inviter_code = (typeof e.invite_code != 'undefined') ? e.invite_code : ''
				let codes = Cache.get('invite_code')
				this.register.inviter_code = codes ? codes : ''

				this.developmentHandler({
					inviter_code: this.register.inviter_code
				})
				this.registerFun = trottle(this.registerFun);
				this.wechatQrcode = uni.getStorageSync('self_config')['wechat_qrcode']
			}, 1500)
		},
	};
</script>

<style lang="scss">
	page {
		background-color: white;
		// background-image: url();
	}

	.wananchi_list {
		width: 500rpx;
		height: 600rpx;
		background-color: #FFFFFF;
		border-radius: 30rpx;
		text-align: center;
		position: relative;

		view {
			font-size: 38rpx;
			font-weight: bold;
			padding-top: 35rpx;
		}

		image {
			width: 300rpx;
			height: 300rpx;
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
		}
	}

	.obtainSj {
		width: 100%;
		height: 80rpx;
		text-align: center;
		line-height: 80rpx;
		background-color: #cccccc;
		margin-top: 25rpx;
	}

	.bot_tox {
		border: 0rpx solid #fff;
		padding-left: 0rpx !important;
		padding-right: 0rpx !important;
	}

	.register {
		padding: 60rpx;

		.butoo {
			width: 150rpx;
			height: 150rpx;
			border-radius: 50%;
			background-color: #e5e5e5;

			image {
				width: 150rpx;
				height: 150rpx;
				border-radius: 50%;
			}
		}

		&-text {
			font-size: 53rpx;
			color: #000000;
			font-weight: 700;
		}

		.input {
			border-bottom: 1px solid #cccccc;
			height: 100rpx;
			// border-radius: 12rpx;
			display: flex;
			align-items: center;
		}

		.sms-btn {
			text-align: center;
			@include font_color();
			border-left: $-solid-border;
		}

		.agreement {
			@include font_color;
		}

		.btn {
			margin-top: 40rpx;
			width: 100%;
			height: 100rpx;
			line-height: 100rpx;
			font-size: 32rpx;
			border-radius: 12rpx;
			color: #fff;
			font-weight: 700;
			background-color: #ff8200;
		}

		.disabled {
			opacity: 0.5;
		}
	}

	.comfirm-box {
		text-align: center;
		padding: 60rpx 0 70rpx 0;
	}

	.field-left-icon {
		width: 22rpx;
		height: 30rpx;
	}

	.inytr {
		margin-top: 40rpx;
		margin-left: 15rpx;
		display: flex;
		justify-content: space-between;
		// width: 430rpx;

		.ypolx {
			font-family: Microsoft YaHei;
			font-weight: bold;
			font-size: 26rpx;
			color: #000000;
		}

		.ypolx1 {
			font-family: Microsoft YaHei;
			font-weight: 400;
			font-size: 22rpx;
			color: #000000;
		}
	}

	.register-susses-popup-content {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		width: 479rpx;
		height: 414rpx;
		background: #FFFFFF;
		box-shadow: 1rpx 1rpx 0rpx 0rpx #000000, 0rpx 1rpx 2rpx 0rpx #FFFFFF, 0rpx 1rpx 2rpx 0rpx #FFFFFF;
		border-radius: 51rpx;

		.img {}

		.tip {

			font-family: Microsoft YaHei;
			font-weight: bold;
			font-size: 53rpx;
			color: #666666;
			margin: 20rpx 0 60rpx;
		}

		.btn {
			width: 217rpx;
			height: 72rpx;
			background-color: #ff8200;
			border-radius: 9999rpx;
			// opacity: 0.58;
		}
	}
</style>